﻿local BInventory = AphesLootBrowserGetBabble("LibBabble-Inventory-3.0")
local BFaction = AphesLootBrowserGetBabble("LibBabble-Faction-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("AphesLootBrowser")

local ALB = CreateFrame("Frame", "AphesLootBrowser", UIParent)
ALB:SetScript("OnEvent", function(self, event, ...) if self[event] then return self[event](self, event, ...) end end)

ALB.droptext = {}
BINDING_HEADER_HEADERALB = L["AphesLootBrowser"]
BINDING_NAME_TOGGLEALB = L["show/hide ALB"]

ALB_VERSION = 4.2
ALB_REVISION = 20


local tooltip = CreateFrame("GameTooltip", "ALB_Tooltip", UIParent, "GameTooltipTemplate")
tooltip:SetOwner(WorldFrame, "ANCHOR_NONE")


local unknownItems = {}
local queryall = false

local VALORSOURCE = {
	"Zandalari: 140/instance (7/week)",
	"Heroic: 70/instance (daily)",
	"10-man raid: 70/boss",
	"25-man raid: 105/boss"
}

local JUSTICESOURCE = {
	"Zandalari: 70/boss",
	"heroic: 70/boss",
	"normal: 140/instance (daily)",
}

local TREESOURCE = {
	"Molten Front daily Quests",
}

local GREY = "|cff999999"
local RED = "|cffff0000"
local WHITE = "|cffFFFFFF"
local GREEN = "|cff1eff00"
local PURPLE = "|cff9F3FFF"
local BLUE = "|cff0070dd"

local ORANGE = "|cffFF8400"
local INDENT = "|TInterface\\OptionsFrame\\UI-OptionsFrame-NewFeatureIcon:0:0:0:-1|t  "
local HARDMODE = "|TInterface\\EncounterJournal\\UI-EJ-HeroicTextIcon:19:19:0:0|t "
local ALLIANCE = "|TInterface\\BattlefieldFrame\\Battleground-Alliance:22:22:0:0|t"
local HORDE = "|TInterface\\BattlefieldFrame\\Battleground-Horde:22:22:0:0|t"
local ALLIANCEICON = "Interface\\BattlefieldFrame\\Battleground-Alliance"
local HORDEICON = "Interface\\BattlefieldFrame\\Battleground-Horde"

ALB.CLASSICON = {}
for i = 1, #CLASS_SORT_ORDER do
	ALB.CLASSICON[CLASS_SORT_ORDER[i]] = "|TInterface\\Addons\\AphesLootBrowser\\Icons\\"..CLASS_SORT_ORDER[i]..":22:22:0:0|t"
end

local StatIcons = {
		[format("%s (%s)", _G.ITEM_MOD_SPELL_POWER_SHORT,_G.ITEM_MOD_HIT_RATING_SHORT)] = "|TInterface\\Icons\\Spell_Fire_Fireball02:30:30:0:0|t",
		[_G.ITEM_MOD_SPIRIT_SHORT] = "|TInterface\\Icons\\Spell_Holy_DivineSpirit:30:30:0:0|t",
		[_G.ITEM_MOD_SPELL_POWER_SHORT] = "|TInterface\\Icons\\Spell_Holy_Heal:30:30:0:0|t",
		[_G.DEFENSE] = "|TInterface\\Icons\\Ability_Warrior_DefensiveStance:30:30:0:0|t",
		[_G.ITEM_MOD_AGILITY_SHORT] = "|TInterface\\Icons\\Ability_Rogue_Rupture:30:30:0:0|t",
		[_G.ITEM_MOD_STRENGTH_SHORT] = "|TInterface\\Icons\\Ability_Warrior_OffensiveStance:30:30:0:0|t",
		["?"] = "|TInterface\\Icons\\INV_Misc_QuestionMark:30:30:0:0|t",
}

local Sounds = {
	"Sound\\Character\\Human\\HumanVocalMale\\HumanMaleCheer01.wav",
	"Sound\\Character\\Dwarf\\DwarfVocalMale\\DwarfMaleCheer01.wav",
	"Sound\\Character\\Gnome\\GnomeVocalMale\\GnomeMaleCheer01.wav",
	"Sound\\Character\\NightElf\\NightElfVocalMale\\NightElfMaleCheer02.wav",
	"Sound\\Character\\Draenei\\DraeneiMaleCheer01.wav",
	"Sound\\Character\\Tauren\\TaurenVocalMale\\TaurenMaleCheer01.wav",
	"Sound\\Character\\Scourge\\ScourgeVocalMale\\UndeadMaleCheer02.wav",
	"Sound\\Character\\Troll\\TrollVocalMale\\TrollMaleCheer01.wav",
	"Sound\\Character\\Orc\\OrcVocalMale\\OrcMaleCheer01.wav",
	"Sound\\Character\\BloodElf\\BloodElfMaleCheer01.wav",	
	"Sound\\Character\\Human\\HumanVocalFemale\\HumanFemaleCheer01.wav",
	"Sound\\Character\\Dwarf\\DwarfVocalFemale\\DwarfFemaleCheer01.wav",
	"Sound\\Character\\Gnome\\GnomeVocalFemale\\GnomeFemaleCheer01.wav",
	"Sound\\Character\\NightElf\\NightElfVocalFemale\\NightElfFemaleCheer02.wav",
	"Sound\\Character\\Draenei\\DraeneiFemaleCheer01.wav",
	"Sound\\Character\\Tauren\\TaurenVocalFemale\\TaurenFemaleCheer02.wav",
	"Sound\\Character\\Scourge\\ScourgeVocalFemale\\UndeadFemaleCheer01.wav",
	"Sound\\Character\\Troll\\TrollVocalFemale\\TrollFemaleCheer01.wav",
	"Sound\\Character\\Orc\\OrcVocalFemale\\OrcFemaleCheer01.wav",
	"Sound\\Character\\BloodElf\\BloodElfFemaleCheer01.wav",
	}

ALB_MENUORDER = {
	"Raid 25",
	"Raid 10",	
	"5heroic",
	"5normal",
	"ALB_Cata_Currency",
	"ALB_Cata_Rep",
	"ALB_Cata_Raids",
	"ALB_Cata_5Mans_hero",
	"ALB_Cata_5Mans_normal",
	"ALB_WotLK_Raids25",
	"ALB_WotLK_Raids10",
	"ALB_WotLK_5Mans_hero",
	"ALB_WotLK_5Mans_normal",
	"ALB_WotLK_Emblems",
	"ALB_WotLK_Tokens",
	"ALB_BC_5Mans_hero",
	"ALB_BC_5Mans_normal",
	"ALB_Original_5Mans",
	"ALB_WotLK_Crafting",
--[[	"ALB_WotLK_Reputation",
	"ALB_WotLK_TierSets10",
	"ALB_WotLK_TierSets10hero",
	"ALB_WotLK_TierSets25",
	"ALB_WotLK_TierSets25hero",
--]]
}


local ClassColor = {}
for class, color in pairs(RAID_CLASS_COLORS) do
	ClassColor[class] = string.format("%s%02x%02x%02x", "|cFF", color.r * 255, color.g * 255, color.b * 255)
end

function ALB:pri(text)
	if text and tostring(text) then 
		text = format("%s%s %s", PURPLE, "ALB: |r", tostring(text))
		if ChatFrame3 and ChatFrame3:IsVisible() then
			ChatFrame3:AddMessage(tostring(text)) 
		else
			DEFAULT_CHAT_FRAME:AddMessage(tostring(text)) 
		end
	end
end

function ALB:GetBossLocation(id)  --rename this function 
	local location, source = "", ""
	for instance, infos in pairs(ALB_Group) do
		for i = 1, #infos.sources do
			if infos.sources[i] == id then 
				location = infos.name
				source = instance
			end
		end
		if location ~= "" then break end
	end
	return location, source
end

function ALB:GetItemGroup(id)
	local sourcetable = {}
	local cost = ALB:GetItemCost(id)
	if cost then table.insert(sourcetable, {text = cost}) end
	
	if id == 395 then
		for i = 1, #JUSTICESOURCE do
			table.insert(sourcetable, {text = JUSTICESOURCE[i]}) 
		end
		return sourcetable
	elseif id == 396 then
		for i = 1, #VALORSOURCE do
			table.insert(sourcetable, {text = VALORSOURCE[i]}) 
		end
		return sourcetable
	elseif id == 416 then
		for i = 1, #TREESOURCE do
			table.insert(sourcetable, {text = TREESOURCE[i]}) 
		end
		return sourcetable
	end
	
	local item, group, source
	for header, groups in pairs(ALB_Menu) do
		for g = 1, #groups do
			group = groups[g]
			local checkhm, checknorm = false, false
			for s = 1, #ALB_Group[group].sources do
				source = ALB_Group[group].sources[s]
				for i = 1, #ALB_Source[source].items do
					item = ALB_Source[source].items[i]
					if item == id and ALB_Source[source].type == "boss" then
						if ALB_Source[source].mode == "hardmode" then
							checkhm = true
						else
							checknorm = true
						end
					end
				end
			end
			if checkhm then
				table.insert(sourcetable, {text = format("%s %s %s", ALB:GetGroupName(group), ALB_Group[group].size, L["heroic"])})
			end
			if checknorm then
				table.insert(sourcetable, {text = format("%s %s", ALB:GetGroupName(group), ALB_Group[group].size)})
			end
		end		
	end
	return sourcetable
end

function ALB:GetItemSource(id, wholetable, short)
	if not wholetable then
		local source = ALB:GetItemCost(id) or ""
		for sourceID, info in pairs(ALB_Source) do
			for i = 1, #info.items do
				if info.items[i] == id then 
					if short then return sourceID end					
					if ALB_Source[sourceID].type == "boss" 
					or ALB_Source[sourceID].type == "crafting" then
						if source ~= "" then 
							local size= strmatch(source, "^"..ALB_Source[sourceID].name.." (%d%d)")
							if size then					
								local hero = strmatch(source, "^"..ALB_Source[sourceID].name.." %d%d "..L["heroic"].."$")
								if hero then
									if ALB_Source[sourceID].mode == "heroic" then
										source = ALB_Source[sourceID].name .. " 10/25 "..L["heroic"]								
									else
										source = L["multiple"]; break 
									end
								else
									source = ALB_Source[sourceID].name .. " 10/25"
								end
							else	
								source = L["multiple"]; break 
							end
						else
							source = ALB_Source[sourceID].name .. " " .. ALB:BossTypeToText(ALB_Source[sourceID])
						end
					elseif ALB_Source[sourceID].type == "faction" then
						if source ~= "" then source = L["multiple"]; break end
						source = format("%s: %s", ALB_Source[sourceID].name, ALB_Source[sourceID].rep)
					elseif ALB_Source[sourceID].type == "currency" then
						if source ~= "" then break end
						source = format("%s: %s", ALB_Source[sourceID].name, ALB_Source[sourceID].info)
					elseif ALB_Source[sourceID].type == "token" then
						if source ~= "" then break end
						source = format("%s: %s", ALB_Source[sourceID].name, ALB_Source[sourceID].info)
					end
				end
			end
		end
		if source == "" then source = "?" end
		return source
	else
		local sourcetable = {}
		local cost = ALB:GetItemCost(id)
		if cost then table.insert(sourcetable, {text = cost, token=true}) end
		local item, group, source
		for header, groups in pairs(ALB_Menu) do
			for g = 1, #groups do
				group = groups[g]
				for s = 1, #ALB_Group[group].sources do
					source = ALB_Group[group].sources[s]
					for i = 1, #ALB_Source[source].items do
						item = ALB_Source[source].items[i]
						if item == id then 	
							if ALB_Source[source].type == "boss" then
								table.insert(sourcetable, {
									text = "|T".. ALB_Source[source].image .. ":20:40:0:0|t"..ALB_Source[source].name .. " " .. ALB:BossTypeToText(ALB_Source[source]),
									ExpandedHeaders = {header, group},
									SelectedInstance = source,
									})							
							elseif ALB_Source[source].type == "faction" then
								table.insert(sourcetable, {
									text = format("%s: %s", ALB_Source[source].name, ALB_Source[source].rep),
									ExpandedHeaders = {header, group},
									SelectedInstance = source,
									})							
							elseif ALB_Source[source].type == "currency" 
								or ALB_Source[source].type == "token" then
								table.insert(sourcetable, {
									text = format("%s: %s", ALB_Source[source].name, ALB_Source[source].info),
									ExpandedHeaders = {header, group},
									SelectedInstance = source,
									})	
							end
							
						end
					end
				end
			end		
		end
		return sourcetable
	end
end

function ALB:BossTypeToText(tab)  -- rename this function
	if tab.type == "boss" then
		if tab.size > 5 then
			return tab.size .. 
				(tab.mode == "heroic" and " "..L["heroic"] or "")
		else
			return tab.mode == "heroic" and L["heroic"] or "normal"
		end
	elseif tab.type == "instance" then
		return tab.mode == "heroic" and L["heroic"] or ""
	elseif tab.type == "currency" then
		return tab.cost
	elseif tab.type == "crafting" then
		return format("(%s)", GetSpellInfo(tab.id))
	end	
	return " "
end

function ALB:GetGroupName(GroupId)
	if ALB_Group[GroupId].type == "instance" then
		if ALB_Group[GroupId].size < 10 then
			return format("%s %s", ALB_Group[GroupId].name, ALB:BossTypeToText(ALB_Group[GroupId]))
		else
			return ALB_Group[GroupId].name or ALB_Group[GroupId].name
		end
	elseif ALB_Group[GroupId].type == "currency" then
		return ALB_Group[GroupId].name
	elseif ALB_Group[GroupId].type == "token" then
		return ALB_Group[GroupId].name
	elseif ALB_Group[GroupId].type == "faction" then
		return format("%s%s",
			ALB_Group[GroupId].horde and ALB_Group[GroupId].alliance and "  " or 
			ALB_Group[GroupId].alliance and ALLIANCE or
			ALB_Group[GroupId].horde and HORDE
			or "  ",
			ALB_Group[GroupId].name)
	elseif ALB_Group[GroupId].type == "set" then
		return ALB_Group[GroupId].name 
	elseif ALB_Group[GroupId].type == "crafting" then
		return ALB_Group[GroupId].name
	end
end

function ALB:GetSourceName(source)
	if ALB_Source[source].type == "boss" then
		return format("%s%s", (ALB_Source[source].mode == "heroic") and HARDMODE or "", ALB_Source[source].name or "WTF")
	elseif ALB_Source[source].type == "currency" then
		return format("%s %s", ALB_Source[source].name, ALB_Source[source].info or ALB_Source[source].cost)
	elseif ALB_Source[source].type == "token" then
		return format("%s %s", ALB_Source[source].name, ALB_Source[source].info)
	elseif ALB_Source[source].type == "faction" then
		return format("%s %s", ALB_Source[source].name, ALB_Source[source].rep)
	elseif ALB_Source[source].type == "set" then
		return format("T%s %s %s", ALB_Source[source].tier, L[ALB_Source[source].version], ALB_Source[source].ilvl)
	elseif ALB_Source[source].type == "crafting" then
		return ALB_Source[source].name
	end
end

function ALB:GetItemCost(itemId, detailed)
	if not detailed then
		
		local token1icon,token1name,token2icon,token2name 
		if itemId and ALB_Item[itemId] and ALB_Item[itemId].cost then
			token1icon = GetItemIcon(ALB_Item[itemId].cost[1]) or format("Interface\\Icons\\%s", select(3, GetCurrencyInfo(ALB_Item[itemId].cost[1])))
			
			if #ALB_Item[itemId].cost == 4 then
				token2icon = GetItemIcon(ALB_Item[itemId].cost[3]) or format("Interface\\Icons\\%s", select(3, GetCurrencyInfo(ALB_Item[itemId].cost[3])))				
				return format("%s |T%s:17:17:0:0|t+%s |T%s:17:17:0:0|t", ALB_Item[itemId].cost[2], token1icon, ALB_Item[itemId].cost[4], token2icon)
			else
				return format("%s |T%s:17:17:0:0|t", ALB_Item[itemId].cost[2], token1icon)
			end
		end
	elseif itemId and ALB_Item[itemId] and ALB_Item[itemId].cost then
		if #ALB_Item[itemId].cost == 4 then
			return ALB_Item[itemId].cost[2], ALB_Item[itemId].cost[1], ALB_Item[itemId].cost[4], ALB_Item[itemId].cost[3]
		else
			return ALB_Item[itemId].cost[2], ALB_Item[itemId].cost[1]
		end
	end
	return nil
end

function ALB:GetCleverItemInfo(itemType, itemSubType, itemEquiploc, itemId)
	local itemtype, itemsubtype, itemequiploc, itemid = itemType, itemSubType, itemEquiploc, itemId
	local faction = ""
	if itemid and ALB_Item[itemid] and ALB_Item[itemid].faction then
		faction = ALB_Item[itemid].faction == "ALLIANCE" and ALLIANCE
				or ALB_Item[itemid].faction == "HORDE" and HORDE
	end
	if ALB_Item[itemid].class and ALB.CLASSICON[ALB_Item[itemid].class] then
		faction = faction .. ALB.CLASSICON[ALB_Item[itemid].class]
	end
	if itemtype == BInventory["Armor"] then
		if itemsubtype == BInventory["Miscellaneous"] or
				itemsubtype == BInventory["Shields"] or
				itemsubtype == BInventory["Librams"] or
				itemsubtype == BInventory["Idols"] or
				itemsubtype == BInventory["Totems"] then
			return format("%s %s", faction, _G[itemequiploc] or "")
		else
			return format("%s %s, %s", faction, _G[itemequiploc], itemsubtype)
		end
	elseif itemtype == BInventory["Weapon"] then
		if itemsubtype == BInventory["Daggers"] or
				itemsubtype == BInventory["Fist Weapons"] or
				itemsubtype == BInventory["One-Handed Axes"] or
				itemsubtype == BInventory["One-Handed Maces"] or
				itemsubtype == BInventory["One-Handed Swords"] then
			return  format("%s %s %s", faction, itemsubtype, (_G[itemequiploc] == INVTYPE_WEAPON and "" or " (".._G[itemequiploc]..")"))
		elseif itemsubtype == BInventory["Miscellaneous"] then
			return  format("%s %s (%s)", faction, itemtype, _G[itemequiploc])
		else
			return  format("%s %s", faction, itemsubtype)
		end
	elseif itemtype == BInventory["Quest"] then
		return  format("%s %s", faction, itemtype)
	elseif itemtype == "Money" then
		return CURRENCY
	else
		return  format("%s %s %s", faction, itemtype, itemtype == itemsubtype and "" or " ("..itemsubtype..")")
	end
	
end

------------------------------------------------------------------------
-----------          Items n icons  stuff                -----------------
------------------------------------------------------------------------

function ALB:ItemEnter()
	if not self:GetParent().id then return end	
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
	if self:GetParent().link then
		-- special case in compareframe: items with custom gems/enchants
		GameTooltip:SetHyperlink(
			"item:"..self:GetParent().id..":"..
			self:GetParent().enchant..":"..
			self:GetParent().gems[1]..":"..
			self:GetParent().gems[2]..":"..
			self:GetParent().gems[3]	)
		GameTooltip:AddLine("|n|T"..GetItemIcon(21191)..":25:25:0:0|t"..
			RED.." AphesLootBrowser:")
		GameTooltip:AddLine(INDENT..GREEN..L["shift-click to create a chat link."])
	elseif type(self:GetParent().id) == "number" then
		-- basically all itemicons 
		SetCursor("INSPECT_CURSOR")
		if self:GetParent().save then
			GameTooltip:SetHyperlink("item:"..self:GetParent().id)
			GameTooltip:AddLine("|n|T"..GetItemIcon(21191)..":25:25:0:0|t"..
				RED.." AphesLootBrowser:")
			GameTooltip:AddLine(INDENT..GREEN..L["right-click for options"])
		else
			GameTooltip:SetText(RED..L["unsave warning"])
			GameTooltip:AddLine("|r"..L["unsave details1"])
			GameTooltip:AddLine("|r"..L["unsave details2"])
			GameTooltip:AddLine("|n"..GREEN..L["right-click for options"])
		end
	elseif type(self:GetParent().id) == "string" then
		-- icons in compare menu
		GameTooltip:SetHyperlink(self:GetParent().id)
	end
	if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
	GameTooltip:Show()
end


local stats = {}
function ALB:DetailItemTooltip()
	if not (self.id or self:GetParent().id) then return end
	local ItemId = self.id or self:GetParent().id
	local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, _, itemEquipLoc, itemTexture = GetItemInfo(ItemId) 
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
	if ALB_Item[ItemId] and ALB_Item[ItemId].spell then
		GameTooltip:SetHyperlink("spell:"..ALB_Item[ItemId].spell)
		GameTooltip:AddLine(" ")
	end
	if itemName then 
		GameTooltip:AddLine(itemName, GetItemQualityColor(itemRarity))
		wipe(stats)
		GetItemStats(itemLink, stats)	
		local stattype = 
			stats.ITEM_MOD_SPIRIT_SHORT and _G.ITEM_MOD_SPIRIT_SHORT or
			stats.ITEM_MOD_INTELLECT_SHORT and stats.ITEM_MOD_HIT_RATING_SHORT and format("%s (%s)", _G.ITEM_MOD_SPELL_POWER_SHORT,_G.ITEM_MOD_HIT_RATING_SHORT) or
			stats.ITEM_MOD_INTELLECT_SHORT and _G.ITEM_MOD_SPELL_POWER_SHORT or
			(stats.ITEM_MOD_DEFENSE_SKILL_RATING_SHORT or stats.ITEM_MOD_DODGE_RATING_SHORT or stats.ITEM_MOD_PARRY_RATING_SHORT or stats.ITEM_MOD_BLOCK_RATING_SHORT) and _G.DEFENSE or
			stats.ITEM_MOD_AGILITY_SHORT and _G.ITEM_MOD_AGILITY_SHORT or
			stats.ITEM_MOD_STRENGTH_SHORT and _G.ITEM_MOD_STRENGTH_SHORT or "?"
		GameTooltip:AddDoubleLine(format("%s: %s", L["ilvl"], itemLevel), ALB:GetCleverItemInfo(itemType, itemSubType, itemEquipLoc, ItemId))
		if stattype then
			GameTooltip:AddLine(format("%s  %s%s|r", StatIcons[stattype], GREEN, stattype))
		end
		
		if IsAddOnLoaded("Pawn") then  --PAWN
			local scales = PawnGetAllScalesEx() 
			local item
			local value = 0
			if scales then
				item = PawnGetItemData(itemLink)
				GameTooltip:AddLine("|nPawn:")
				for i = 1, #scales do
					if scales[i].IsVisible then
						value = format("%.1f", select(2, PawnGetSingleValueFromItem(item, scales[i].Name)) or 0)
						UpgradeInfo = PawnIsItemAnUpgrade(item)
						local ThisUpgrade, WasUpgrade = true, false
						if UpgradeInfo then
							for _, ThisUpgrade in pairs(UpgradeInfo) do								
								if ThisUpgrade.ScaleName == scales[i].Name then
									WasUpgrade = true
									break
								end
							end
						end
						if WasUpgrade then
						GameTooltip:AddLine(format("      |cFF%s%s: %s    |TInterface\\AddOns\\Pawn\\Textures\\UpgradeArrow:0|t|r Upgrade",PawnCommon.Scales[scales[i].Name].Color ,scales[i].LocalizedName, value))
						else
						GameTooltip:AddLine(format("      |cFF%s%s: %s|r",PawnCommon.Scales[scales[i].Name].Color ,scales[i].LocalizedName, value))
						end
					end
				end
			end
		end
		
	else
		GameTooltip:AddLine(ALB_Item[ItemId] and ALB_Item[ItemId].name or format("item: %s", ItemId), GetItemQualityColor(0))
		GameTooltip:AddLine(format("%s: %s", L["ilvl"], ALB_Item[ItemId] and ALB_Item[ItemId].ilvl or "?"))
	end
	local sources = ALB:GetItemSource(ItemId, true)
	if sources and #sources > 1 then
		GameTooltip:AddLine(format("|n%s:|n", L["source"]))
		for i = 1, 4 do
			if sources[i] then GameTooltip:AddLine(format("    - %s",sources[i].text)) end
		end
		if sources[5] then GameTooltip:AddLine("  ... etc") end
	elseif sources[1] then
		GameTooltip:AddLine(format("|n%s: %s", L["source"], sources[1].text))
	end
	local cost1, token1, cost2, token2 = ALB:GetItemCost(ItemId, true)
	if cost1 then
	
		local token1icon = GetItemIcon(token1) or format("Interface\\Icons\\%s", select(3, GetCurrencyInfo(ALB_Item[ItemId].cost[1])))
		local token1name = GetItemInfo(token1) or GetCurrencyInfo(ALB_Item[ItemId].cost[1])
	
		GameTooltip:AddLine("|n|n")
		GameTooltip:AddLine(format("|T%s:17:17:0:0|t %s:", token1icon, token1name))
		sources = ALB:GetItemGroup(token1)
		if sources and #sources > 1 then
			for i = 1, 4 do
				if sources[i] then GameTooltip:AddLine(format("    - %s",sources[i].text)) end
			end
			if sources[5] then GameTooltip:AddLine("    ...") end
		elseif sources[1] then
			GameTooltip:AddLine(format("    %s", sources[1].text))
		end
		if cost2 and token2 ~= 34518 then
		
			local token2icon = GetItemIcon(token2) or format("Interface\\Icons\\%s", select(3, GetCurrencyInfo(ALB_Item[ItemId].cost[3])))
			local token2name = GetItemInfo(token2) or GetCurrencyInfo(ALB_Item[ItemId].cost[3])
		
			GameTooltip:AddLine(format("|n|T%s:17:17:0:0|t %s:", token2icon, token2name))
			sources = ALB:GetItemGroup(token2)
			if sources and #sources > 1 then
				for i = 1, 4 do
					if sources[i] then GameTooltip:AddLine(format("    - %s",sources[i].text)) end
				end
				if sources[5] then GameTooltip:AddLine("    ...") end
			elseif sources[1] then
				GameTooltip:AddLine(format("    %s", sources[1].text))
			end
		end		
	end	
	GameTooltip:Show()
end


local tooltip_timer = 0
function ALB:ItemTooltipUpdate(elapsed)
	if not (self == GameTooltip:GetOwner()) then return end
	tooltip_timer = tooltip_timer + elapsed
	if tooltip_timer > 1 then
		tooltip_timer = 0
		AphesLootBrowser.ItemEnter(self)
	end
end

local function AddToNewWishlist(self, arg1, arg2)
	ALB.newWishItem = tonumber(arg1)
	ALB:CreateNewWishlist()
end

local ItemMenu = {}
function ALB:ItemContextMenu(level)
	ItemMenu = UIDropDownMenu_CreateInfo()
	level = level or 1
	ItemMenu.arg1 = self.id or self:GetParent().id
	if level == 1 then
		ItemMenu.hasArrow = false
		if self:GetParent().save then
		-- if safe:
			-- 1 Detail 
			if not (ALBDetail and ALBDetail:IsVisible()) then
			ItemMenu.text = L["open in detail"]
			ItemMenu.func = AphesLootBrowser.LoadToDetailFrame
			UIDropDownMenu_AddButton(ItemMenu, level)
			end
			--2 Compare 
			if not (ALBCompare and ALBCompare:IsVisible()) then
			ItemMenu.text = L["add to compare"]
			ItemMenu.func = AphesLootBrowser.AddToCompare
			UIDropDownMenu_AddButton(ItemMenu, level)
			end
		-- else
		else
			--query
			ItemMenu.text = L["query server"]
			ItemMenu.func = AphesLootBrowser.QueryNextItem
			UIDropDownMenu_AddButton(ItemMenu, level)			
		end
		-- 3 Wishlist always
		ItemMenu.hasArrow = true
		ItemMenu.text = L["add to wishlist"]
		ItemMenu.func = nil
		UIDropDownMenu_AddButton(ItemMenu, level)	
	elseif level == 2 then		
		ItemMenu.text = NEW
		ItemMenu.func = AddToNewWishlist
		UIDropDownMenu_AddButton(ItemMenu, level)
		local listname, character
		for namecode, info in pairs(ALB_WISHLIST["#ME#"]) do
			listname, character = string.match(namecode, "(.+)@(.+)")
			if UnitName("player") == character then		
				ItemMenu.arg2 = listname
				ItemMenu.text = format("%q", listname)
				ItemMenu.func = AphesLootBrowser.AddToWishlist
				UIDropDownMenu_AddButton(ItemMenu, level)
			end
		end
	end
end

function ALB:ItemClick(itemid, button, down)
	if not itemid then return end
	if type(itemid) == "number" then
		-- basically all itemicons 
		if button == "LeftButton" and (self:GetParent().save or self.save) then
			if IsModifiedClick("DRESSUP") then 
				DressUpItemLink(itemid)
			elseif IsModifiedClick("CHATLINK") then 
				ChatEdit_InsertLink(select(2, GetItemInfo(itemid)))
			end
		elseif button == "RightButton" then	
			local frame = self
			if not self:GetParent().id then frame = _G[self:GetName() .. "Icon"] end
			ToggleDropDownMenu(nil, nil, frame)
		end
	else
		-- special case in compareframe
		PickupItem(itemid)
	end
end

function ALB:WishlistClick(itemid)
	if not itemid then return end
	ToggleDropDownMenu(nil, nil, self)
end

function ALB.MainFrameLoad()
	ALBMainMenuBrowserText:SetText(L["browse"])
	ALBMainMenuSearchText:SetText(L["search"])
	ALBMainMenuDetailText:SetText(L["detail"])
	ALBMainMenuCompareText:SetText(L["compare"])
	ALBMainMenuWishlistText:SetText(L["wishlist"])
	ALBFrameOptions:SetText(L["options"])
	ALBMainMenuBrowserActive:Show()
	
	ALBMessageFrame:SetTimeVisible(2)
	
	ALBFrame:RegisterForDrag("LeftButton")
	tinsert(UISpecialFrames, "ALBFrame")			
end

------------------------------------------------------------------------
-----------          Roll frame wishlist               -----------------
------------------------------------------------------------------------
local function OnRoll(f, event, id)
	if f.id ~= id then return end
	f.id = nil
	f:Hide()
end

local RollWishFrames
local function CreateRollWishFrames()
	RollWishFrames = {}
	local f
	for i = 1, 4 do
		f = CreateFrame("Frame", "ALB"..i, _G["GroupLootFrame"..i], "RollWishFrame")
		f:SetScript("OnEvent", OnRoll)
		f:RegisterEvent("CANCEL_LOOT_ROLL")
		f.wish = _G["ALB"..i.."Wish"]
		f.wishframe = _G["ALB"..i.."Wishframe"]
		f.wishlist = _G["ALB"..i.."WishframeText"]
		f:Hide()
		table.insert(RollWishFrames, f)		
	end
end

local function GetFrame(id)
	if not RollWishFrames then CreateRollWishFrames() end
	for _,f in ipairs(RollWishFrames) do
		if not f.id then return f end
	end
end

function ALB:START_LOOT_ROLL(self, id, timer)
	if ALB_SETTINGS.RollFrameWishlists or ALB_SETTINGS.PlaySounds then 
		local itemid = tonumber(GetLootRollItemLink(id):match("item:(%d+):"))
		if not itemid then return end
		local f
		if ALB_SETTINGS.RollFrameWishlists then
			f = GetFrame(id)
			f.id = id
			f:Show()			
			f.wish:Hide()
			f.wishframe:Hide()
		end
		
		local wishlist = nil
		if ALB_WISHLIST then
			for listname, _ in pairs(ALB_WISHLIST) do
				for name, info in pairs(ALB_WISHLIST[listname]) do
					if name ~= "#sync#" then
						for i = 1, #info.list do
							if itemid == info.list[i] then
								local listname, character = string.match(name, "(.+)@(.+)")
								if UnitExists(character) then
									if not wishlist then wishlist = "    |cffff0000Wunschlisten:" end
									if character == UnitName("player") then 
										if ALB_SETTINGS.RollFrameWishlists then f.wish:Show() end
										PlaySoundFile(ALB_SETTINGS.PlaySound and Sounds[ALB_SETTINGS.Sound] or "")
									end
									character = (ALDclass and ALDclass[character] and ClassColor[ALDclass[character]]..character) or character
									wishlist = wishlist .. "|n   "..format("%s|r (%s)", character, listname)
								end
							end
						end
					end
				end
			end
		end
		if wishlist and ALB_SETTINGS.RollFrameWishlists then
			f.wishframe:Show()
			f.wishlist:SetText(wishlist)	
		end
	end
end

ALB:RegisterEvent("START_LOOT_ROLL")

------------------------------------------------------------------------
-----------           Tooltip hook                -----------------
------------------------------------------------------------------------
local function OnTooltipSetItem(frame, ...)
	if ALB_SETTINGS.ShowWishlistTooltips then
		local name, link = frame:GetItem()
		if link then
			local header = false
			local id = tonumber(link:match("item:(%d+):"))
			for _, lists in pairs(ALB_WISHLIST) do
				for name, info in pairs(lists) do
					if name ~= "#sync#" and info.list and type(info.list) == "table" then
						for i = 1, #info.list do
							if id == info.list[i] then
								if not header then
									frame:AddLine("|n|T"..GetItemIcon(21191)..":20:20:0:0|tALB:|n"..RED..L["wishlist"]..":|n")
									header = true
								end
								local listname, character = string.match(name, "(.+)@(.+)")
								character = (ALDclass and ALDclass[character] and ClassColor[ALDclass[character]]..character) or character
								frame:AddLine(INDENT..format("%s|r (%s)", character, listname))
							end
						end
					end
				end
			end
					
			local sources = ALB:GetItemSource(id, true)
			if #sources >0 then
				if not header then
					frame:AddLine("|n|T"..GetItemIcon(21191)..":20:20:0:0|tALB:|n")
					header = true
				end
				if #sources > 1 then
					frame:AddLine(format("%s:|n", RED..L["source"].."|r"))
					for i = 1, 4 do
						if sources[i] then frame:AddLine(format("    - %s",sources[i].text)) end
					end
					if sources[5] then frame:AddLine("  ... etc") end
				elseif sources[1] then
					frame:AddLine(format("|n%s: %s", L["source"], sources[1].text))
				end
			end
			
			frame:Show()
		end
	end
end

local tip_funcs = {
		"SetAuctionItem", "SetAuctionSellItem", "SetAuctionCompareItem", "SetBagItem", "SetBuybackItem", "SetCraftItem", "SetGuildBankItem", "SetHyperlink",
		"SetHyperlinkCompareItem", "SetInboxItem", "SetInventoryItem", "SetLootItem", "SetLootRollItem", "SetMerchantCompareItem", "SetMerchantItem", "SetQuestItem", 
		"SetSendMailItem", "SetTradePlayerItem", "SetTradeSkillItem", "SetTradeTargetItem", "SetMerchantCostItem",}
		--"SetQuestLogItem"
	
for _,frame in pairs { GameTooltip, ShoppingTooltip1, ShoppingTooltip2, ShoppingTooltip3, 
				ItemRefTooltip, ItemRefShoppingTooltip1, ItemRefShoppingTooltip2, ItemRefShoppingTooltip3 } do
	for _,func in pairs(tip_funcs) do
		if frame and frame[func] then
			hooksecurefunc(frame, func, OnTooltipSetItem)
		end
	end
end

------------------------------------------------------------------------
-----------           MAIN MENU  stuff                -----------------
------------------------------------------------------------------------
function ALB.MainMenuClick(self, button, down)
	PlaySound("igCharacterInfoTab")
	ALBMainMenuBrowserActive:Hide()
	ALBMainMenuSearchActive:Hide()
	ALBMainMenuDetailActive:Hide()
	ALBMainMenuCompareActive:Hide()
	ALBMainMenuWishlistActive:Hide()
	_G[self:GetName() .. "Active"]:Show()
	local id = self:GetID()
	ALBBrowser:Hide()
	CloseDropDownMenus()
	if ALBOptions then ALBOptions:Hide() end
	if ALBSearchFilterPopup and ALBSearchFilterPopup:IsVisible() then ALBSearchFilterPopupDelete:Click() end
	if ALBSearch then ALBSearch:Hide() end
	if ALBDetail then ALBDetail:Hide() end
	if ALBCompare then ALBCompare:Hide() end
	if ALBWishlist then ALBWishlist:Hide() end
	if id == 1 then
		ALBBrowser:Show()
	elseif id == 2 then
		if ALBSearch then ALBSearch:Show()
		else 
			CreateFrame("Frame", "ALBSearch", ALBFrame, "ALBSearch") 
		end
	elseif id == 3 then
		if ALBDetail then ALBDetail:Show()
		else 
			CreateFrame("Frame", "ALBDetail", ALBFrame, "ALBDetail") 
		end
	elseif id == 4 then
		if ALBCompare then ALBCompare:Show()
		else 
			CreateFrame("Frame", "ALBCompare", ALBFrame, "ALBCompare") 
		end
	elseif id == 5 then
		if ALBWishlist then ALBWishlist:Show()
		else 
			CreateFrame("Frame", "ALBWishlist", ALBFrame, "ALBWishlist") 
		end
	end
end

----------------------
--  Minimap Button  --
----------------------

local function moveButton(self)
	local centerX, centerY = Minimap:GetCenter()
	local x, y = GetCursorPosition()
	x, y = x / self:GetEffectiveScale() - centerX, y / self:GetEffectiveScale() - centerY
	centerX, centerY = math.abs(x), math.abs(y)
	centerX, centerY = (centerX / math.sqrt(centerX^2 + centerY^2)) * ALB_SETTINGS.MinimapIconRadius, (centerY / sqrt(centerX^2 + centerY^2)) * ALB_SETTINGS.MinimapIconRadius
	centerX = x < 0 and -centerX or centerX
	centerY = y < 0 and -centerY or centerY
	self:ClearAllPoints()
	self:SetPoint("CENTER", centerX, centerY)
end

function ALB:CreateMinimapButton()
	local button = CreateFrame("Button", "ALBMinimapButton", Minimap, "ALB_MinimapButton")
	button:SetMovable(true)
	button:SetUserPlaced(true)

	button:SetScript("OnMouseDown", function(self, button)
		if IsShiftKeyDown() or button == "RightButton" then
			self:SetScript("OnUpdate", moveButton)
		end
	end)
	button:SetScript("OnMouseUp", function(self)
		self:SetScript("OnUpdate", nil)
	end)
	button:SetScript("OnClick", function(self, button)
		if IsShiftKeyDown() or button == "RightButton" then return end
		ALB:ToggleWindow()
	end)
	button:SetScript("OnEnter", function(self)
		GameTooltip_SetDefaultAnchor(GameTooltip, self)
		GameTooltip:SetText(L["AphesLootBrowser"], 1, 1, 1)
		GameTooltip:AddLine(format(L["Version/Revision"], ALB_VERSION, ALB_REVISION))
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine(GREEN..L["left-click to open/close ALB"])
		GameTooltip:AddLine(GREEN..L["right-click to move"])
		GameTooltip:Show()
	end)
	button:SetScript("OnLeave", function(self)
		GameTooltip:Hide()
	end)
	if not ALB_SETTINGS.ShowMinimapIcon then button:Hide() end
end

function ALB:ToggleMinimapButton()
	ALB_SETTINGS.ShowMinimapIcon = not ALB_SETTINGS.ShowMinimapIcon
	if ALB_SETTINGS.ShowMinimapIcon then
		if ALBMinimapButton then ALBMinimapButton:Show()
		else ALB:CreateMinimapButton() end
	else
		if ALBMinimapButton then ALBMinimapButton:Hide() end
	end
end

function ALB:PositionMinimapButton()
	ALB_SETTINGS.MinimapIconRadius = ALBOptionsMinimapRadius:GetValue()
	local centerX, centerY = Minimap:GetCenter()
	local x, y = ALBMinimapButton:GetCenter()
	x, y = x  - centerX, y  - centerY
	centerX, centerY = math.abs(x), math.abs(y)
	centerX, centerY = (centerX / math.sqrt(centerX^2 + centerY^2)) * ALB_SETTINGS.MinimapIconRadius, (centerY / sqrt(centerX^2 + centerY^2)) * ALB_SETTINGS.MinimapIconRadius
	centerX = x < 0 and -centerX or centerX
	centerY = y < 0 and -centerY or centerY
	ALBMinimapButton:ClearAllPoints()
	ALBMinimapButton:SetPoint("CENTER", centerX, centerY)
end

------------------------------------------------------------------------
-----------           Data-Broker stuff                 -----------------
------------------------------------------------------------------------
LibStub:GetLibrary("LibDataBroker-1.1"):NewDataObject("AphesLootBrowser", {
	type = "launcher",
	label = "ALB",
	OnClick = function(_, btn)
		ALB:ToggleWindow()	
	end,
	icon = "Interface\\Icons\\INV_Holiday_Christmas_Present_01",
	OnTooltipShow = function(tooltip)
		if not tooltip or not tooltip.AddLine then return end
		tooltip:SetText(L["AphesLootBrowser"])	
		tooltip:AddLine(format(L["Version/Revision"], ALB_VERSION, ALB_REVISION))	
		tooltip:AddLine(" ")
		tooltip:AddLine(GREEN..L["left-click to open/close ALB"])
	end,
})

------------------------------------------------------------------------
-----------         OPTIONS                -----------------
------------------------------------------------------------------------
local function SoundChanged(self)
	for i = 1, 20 do
		_G["ALBOptionsRace"..i]:SetChecked(false)
		_G["ALBOptionsRace"..i.."Icon"]:SetDesaturated(1)
	end
	self:SetChecked(1)
	_G[self:GetName().."Icon"]:SetDesaturated(false)
	ALB_SETTINGS.Sound = self:GetID()
	PlaySoundFile(Sounds[self:GetID()])
end

function ALB:OptionsShow()
	if not ALBOptions then
		CreateFrame("Frame", "ALBOptions", ALBFrame, "ALBOptions")
		ALBOptionsHeader:SetText(L["options"])
		ALBOptionsMinimapShowText:SetText(L["show minimap button"])
		ALBOptionsMinimapRadiusText:SetText(L["minimap radius"])
		ALBOptionsTooltipText:SetText(L["show wishlists in item tooltips"])
		ALBOptionsAskRaidSyncText:SetText(L["ask me to import raidmember's wishlists"])
		--ALBOptionsQueryAll:SetText(L["query server"])
		ALBOptionsVersion:SetText(L["ALB versions"])
		ALBOptionsMinimapShow:SetChecked(ALB_SETTINGS.ShowMinimapIcon)
		ALBOptionsMinimapRadius:SetValue(ALB_SETTINGS.MinimapIconRadius)
		ALBOptionsTooltip:SetChecked(ALB_SETTINGS.ShowWishlistTooltips)
		ALBOptionsAskRaidSync:SetChecked(ALB_SETTINGS.AskForRaidsync)
		ALBOptionsMinimapRadius:SetScript("OnValueChanged", AphesLootBrowser.PositionMinimapButton)
		if IsAddOnLoaded("AphesLootDingen") then
			ALBOptionsRollFrameWishlists:Disable()
			ALBOptionsRollFrameWishlists:SetChecked(nil)
			ALBOptionsRollFrameWishlistsText:SetText(format("%s(%s) %s", GREY, ADDON_DISABLED,L["show wishlists next to lootroll frames"]))
		else
			ALBOptionsRollFrameWishlists:SetChecked(ALB_SETTINGS.RollFrameWishlists)
			ALBOptionsRollFrameWishlistsText:SetText(L["show wishlists next to lootroll frames"])
		end
		ALBOptionsPlaySoundsText:SetText(L["Play sound when rolling for an item on your wishlist"])
		ALBOptionsPlaySounds:SetChecked(ALB_SETTINGS.PlaySounds)
		local f 
		local line, column = 1, 1
		for i = 1, 20 do
			f = CreateFrame("CheckButton", "ALBOptionsRace"..i, ALBOptions, "ClassButtonTemplate")
			f:SetPoint("TOPLEFT", i < 11 and 55 + (i * 33) or 55 + ((i- 10) * 33), i < 11 and -310 or -343)
			_G["ALBOptionsRace"..i.."Icon"]:SetTexCoord((column-1)*0.125, column*0.125, (line-1)*0.25 , line*0.25)
			f:SetChecked(i == ALB_SETTINGS.Sound)
			_G["ALBOptionsRace"..i.."Icon"]:SetDesaturated(i ~= ALB_SETTINGS.Sound)
			f:SetID(i)
			f:SetScript("OnClick", SoundChanged)
			column = column + 1
			if column > 5 then
				column = 1
				line = line + 1
			end
		end
	end
	ALBOptions:Show()
end

function ALB:OptionsChanged()
	ALB_SETTINGS.ShowWishlistTooltips = ALBOptionsTooltip:GetChecked() and true or false
	ALB_SETTINGS.AskForRaidsync = ALBOptionsAskRaidSync:GetChecked() and true or false
	ALB_SETTINGS.RollFrameWishlists = ALBOptionsRollFrameWishlists:GetChecked() and true or false
	ALB_SETTINGS.PlaySounds = ALBOptionsPlaySounds:GetChecked() and true or false
	if self:GetName() == "ALBOptionsPlaySounds" and ALB_SETTINGS.PlaySounds then
		PlaySoundFile(Sounds[ALB_SETTINGS.Sound])
	end
end

------------------------------------------------------------------------
-----------         Query ALLL items                 -----------------
------------------------------------------------------------------------
function ALB:QueryAllTooltip()
	GameTooltip:SetOwner(_G["ALBOptionsQueryAll"], "ANCHOR_RIGHT")
	GameTooltip:SetText(L["query server"])
	GameTooltip:AddLine("|n"..L["Queries the server for ALL unsave items."])
	GameTooltip:AddLine(L["This will take ages! But you can continue playing until..."])
	GameTooltip:AddLine(RED..L["You may be disconnected."])
	GameTooltip:Show()
end

function ALB:QueryReallyAll()
	if queryall then return end
	queryall = true
	
	wipe(unknownItems)
	for id,_ in pairs(ALB_Item) do
		GetItemInfo(id)
	end			
		ALB:pri(L["All available itemlists loaded"])
		collectgarbage()
		local f = CreateFrame("Frame", "ALBFrame", UIParent, "ALB_Main")
		f:SetPoint("CENTER", UIParent)
		CreateFrame("Frame", "ALBBrowser", f, "ALBBrowser")
		AphesLootBrowser.UpdateInstanceList()	
	--end
end

function ALB:InitQueryReallyAll()
	wipe(unknownItems)
	for id,_ in pairs(ALB_Item) do
		if not GetItemInfo(id) then
			table.insert(unknownItems, id)
		end
	end
	ALB:ToggleWindow()
	StaticPopupDialogs["ALBQueryAll"].text = format(L["Checking %s unsave items will take approximately %s."], #unknownItems, format("%s%s|r", RED, SecondsToTime(#unknownItems  * 5, false, true)))
	StaticPopup_Show ("ALBQueryAll")	
end

------------------------------------------------------------------------
-----------          Synclinks in chat                 -----------------
------------------------------------------------------------------------ 
local function ChatLink(link, text, button)
	if link and type(link) == "string" and string.find(link, "ALB#(.+)") then
		local _,_, player = string.find(link, "ALB#(.+)")
		ALB:RequestWishlist(player)
		return
	end
	ALB.OriHook(link, text, button)
end
------------------------------------------------------------------------
-----------          Frame create                 -----------------
------------------------------------------------------------------------ 

local function LoadAddons()
	local Addon = {
		"ALB_Cata_Rep",
		"ALB_Cata_Currency",
		}
	for i = 1, #Addon do
		if not IsAddOnLoaded(Addon[i]) then
			LoadAddOn(Addon[i])
		end
	end
	ALB:QueryReallyAll()
end

function ALB:ToggleWindow()
	if _G.ALBEJTimer and _G.ALBEJTimer:IsShown() then return end

	wipe(ALB.droptext)
	
	if ALDDB then
		local tab, itemid, day, boss
		tab = {}
		for i = 1, #ALDDB do
			itemid = tonumber(ALDDB[i].loot:match("item:(%d+):"))
			boss = ALB:GetItemSource(itemid, false, true)
			_,_, day = strfind(ALDDB[i].day, "(%d%d%d%d%d%d)%d%d%d%d")
			if boss and ALB_Source[boss] and ALB_Source[boss].type == "boss" then
				tab[boss] = tab[boss] or {}
				tab[boss].killdate = tab[boss].killdate or {}
				tab[boss].kills = tab[boss].kills or 0
				if not tab[boss].killdate[day] then
					tab[boss].killdate[day] = true
					tab[boss].kills = tab[boss].kills + 1
				end					
				tab[boss].items = tab[boss].items or {}
				tab[boss].items[itemid] = tab[boss].items[itemid] and tab[boss].items[itemid] + 1 or 1
			end			
		end		
		
		for boss, info in pairs(tab) do
			for id, count in pairs(info.items) do
				ALB.droptext[id] = count.."/"..info.kills.."  (".. floor(( ( count / info.kills ) * 100 )+0.5) .. "%)"
			end
		end
	end	
	if not _G.ALBFrame then
		LoadAddons()
	else
		if _G.ALBFrame:IsVisible() then 
			CloseDropDownMenus()
			_G.ALBFrame:Hide()
		else _G.ALBFrame:Show() end
	end
end

local function Presets()
	ALB_SETTINGS = ALB_SETTINGS or {}
	ALB_SETTINGS.ShowMinimapIcon = tostring(ALB_SETTINGS.ShowMinimapIcon) == "nil" and true or ALB_SETTINGS.ShowMinimapIcon
	ALB_SETTINGS.MinimapIconRadius = ALB_SETTINGS.MinimapIconRadius or 80
	ALB_SETTINGS.ShowWishlistTooltips = tostring(ALB_SETTINGS.ShowWishlistTooltips) == "nil" and true or ALB_SETTINGS.ShowWishlistTooltips
	ALB_SETTINGS.AskForRaidsync = tostring(ALB_SETTINGS.AskForRaidsync) == "nil" and true or ALB_SETTINGS.AskForRaidsync
	ALB_SETTINGS.RollFrameWishlists = tostring(ALB_SETTINGS.RollFrameWishlists) == "nil" and true or ALB_SETTINGS.RollFrameWishlists
	ALB_SETTINGS.PlaySounds = ALB_SETTINGS.PlaySounds
	ALB_SETTINGS.Sound = tostring(ALB_SETTINGS.Sound) == "nil" and 13 or ALB_SETTINGS.Sound
end

function ALB:ADDON_LOADED(self, addon)
	if addon ~= "AphesLootBrowser" then return end
	ALB:UnregisterEvent("ADDON_LOADED")
	Presets()
	ALB:CreateCompareTable()
	if not ALB_WISHLIST then 
		ALB_WISHLIST = {} 
		ALB_WISHLIST["#ME#"] = {}
	end
	ALB:CreateMinimapButton()
	ALB.OriHook = SetItemRef
	SetItemRef = ChatLink
--	hooksecurefunc("ChatFrame_OnHyperlinkShow", ChatLink)		
end

function ALB:EJ_LOOT_DATA_RECIEVED(event, id)
	if id then
		ALB_Item[id] = {name =  GetItemInfo(id), ilvl = select(4, GetItemInfo(id))}
	end
end

function ALB:Check_EJ_Loot()	
	local itemcount = 0	
	
	for u = 1, 2 do
	
	local instanceIndex = 1
	local isRaid = u == 2
	local instanceId, instanceName, instanceDesc, nowas, bild = EJ_GetInstanceByIndex(instanceIndex, isRaid)
	local runs = 0
	
		while instanceId do
			EJ_SelectInstance(instanceId)			
			instanceName, instanceDesc, bild = EJ_GetInstanceInfo()			
			if isRaid then
				runs = 4				
			else
				runs = 2
			end
			
			for i = 1, runs do			
				local bossIndex = 1
				local name, desc, bossId = EJ_GetEncounterInfoByIndex(bossIndex)				
				while name and bossIndex < 25 do
					EJ_SelectEncounter(bossId)	
					EJ_SetDifficulty((i == 2 or i == 4), (i==1 or i==2))	
					
						for i = 1,EJ_GetNumLoot() do
							itemcount = itemcount + 1
						end
						
					bossIndex = bossIndex + 1
					name, desc, bossId = EJ_GetEncounterInfoByIndex(bossIndex)
				end
			
			end
			
			instanceIndex = instanceIndex + 1
			instanceId, instanceName, instanceDesc, nowas, bild = EJ_GetInstanceByIndex(instanceIndex, isRaid)
		end
	end
	
	return itemcount
	
end

function ALB:Gather_EJ_Loot()
	
	if not ALB_Item then ALB_Item = {} end
	if not ALB_Source then ALB_Source = {} end
	if not ALB_Menu then ALB_Menu = {} end
	if not ALB_Group then ALB_Group = {} end
	
	local itemcount = 0
	local check = true
	
	for u = 1, 2 do
	
	local instanceIndex = 1
	local isRaid = u == 2
	local instanceId, instanceName, instanceDesc, nowas, bild = EJ_GetInstanceByIndex(instanceIndex, isRaid)
	local runs = 0
	
		while instanceId do
			EJ_SelectInstance(instanceId)
			
			instanceName, instanceDesc, bild = EJ_GetInstanceInfo()
			
			if isRaid then
			
				for num = 1, 2 do		
					local player = num == 1 and 10 or 25
					ALB_Menu["Raid "..player] = ALB_Menu["Raid "..player] or {}
					table.insert(ALB_Menu["Raid "..player], instanceName..player)
					
					ALB_Group[instanceName..player] = {
						name = instanceName,
						type = "instance",
						size = player,
						mode = "hardmode",
						instanceId = instanceId,
						sources = {},
						image = bild,
					}				
				end
				
				runs = 4
				
			else
				
				for num = 1, 2 do
					local mode = num == 1 and "normal" or "heroic"
					
					ALB_Menu["5"..mode] = ALB_Menu["5"..mode] or {}
					table.insert(ALB_Menu["5"..mode], instanceName.."5"..mode)			
					
					ALB_Group[instanceName.."5"..mode] = {
						name = instanceName,
						type = "instance",
						size = 5,
						mode = mode,
						instanceId = instanceId,
						sources = {},
						image = bild,
					}
				end
				runs = 2
			end
			
			for i = 1, runs do
			
				local bossIndex = 1
				local name, desc, bossId = EJ_GetEncounterInfoByIndex(bossIndex)
				
				while name and bossIndex < 25 do
					local size = (runs==2 and "5" or i<3 and "10" or "25")
					local version = (i==2 or i==4) and "heroic" or "normal"
					table.insert(ALB_Group[instanceName..size..(size == "5" and version or "")].sources, name..size..version)
					
					local _, _, _, _, bossImage = EJ_GetCreatureInfo(bossIndex, bossId)
					bossImage = bossImage or select(5,EJ_GetCreatureInfo(1, bossId, instanceId))
					bossImage = bossImage or "Interface\\EncounterJournal\\UI-EJ-BOSS-Default"
							
					EJ_SelectEncounter(bossId)	
					
					ALB_Source[name..size..version] = {
						name = name,
						type = "boss",
						bossId = bossId,
						instanceID = instanceId,
						size = tonumber(size),
						mode = (i==2 or i==4) and "heroic" or "normal",
						items = {},	
						image = bossImage,
					}
					
					--EJ_SetDifficulty(EncounterJournal.isHeroic, EncounterJournal.is10Man)
					EJ_SetDifficulty((i == 2 or i == 4), (i==1 or i==2))	
					
						for i = 1,EJ_GetNumLoot() do
							local iname, _, _, _, itemID = EJ_GetLootInfoByIndex(i)
							check = true
							for x = 1, #ALB_Source[name..size..version].items do
								if ALB_Source[name..size..version].items[x] == itemID then check = false end
							end
							if check then
								itemcount = itemcount + 1
								table.insert(ALB_Source[name..size..version].items, itemID)
								if iname ~= RETRIEVING_ITEM_INFO then
									ALB_Item[itemID] = {name = GetItemInfo(itemID), ilvl = select(4, GetItemInfo(itemID))}
								else
									ALB_Item[itemID] = {name = iname, ilvl = 0}
								end
							end
						end
						
					bossIndex = bossIndex + 1
					name, desc, bossId = EJ_GetEncounterInfoByIndex(bossIndex)
				end
			
			end
			
			instanceIndex = instanceIndex + 1
			instanceId, instanceName, instanceDesc, nowas, bild = EJ_GetInstanceByIndex(instanceIndex, isRaid)
		end
	end
	
	return itemcount
	
end


function ALB:FirstLoad(self)
	local timer = CreateFrame("Frame", "ALBEJTimer", UIParent)
	timer:Hide()
	timer.time = 0
	timer.count = 0
	timer:SetScript("OnUpdate", function (this, elapsed)
			timer.time = timer.time + elapsed
			if timer.time > 1 then			
				timer.count = timer.count + 1
				timer.time = 0
				local count = ALB:Check_EJ_Loot()
				if count > 2850 then
					ALB:Gather_EJ_Loot()
					timer:Hide()
				end
			end
		end)
	timer:Show()
	
end

StaticPopupDialogs["ALBQueryAll"] = {
	button1 = ACCEPT,
	button2 = CANCEL,
	sound = "JewelcraftingFinalize",
	whileDead = 1,
	hideOnEscape = 1,
	timeout = 0,
	OnAccept = function() ALB:QueryReallyAll() end,
	OnCancel = function() ALB:ToggleWindow() end
	}

SLASH_APHESLOOTBROWSER1 = "/ALB"
SLASH_APHESLOOTBROWSER2 = "/AphesLootBrowser"
SlashCmdList["APHESLOOTBROWSER"] = function(arg) 
	ALB:ToggleWindow()
end

SLASH_APHESLOOTBROWSERVERSIONCHECK1 = "/ALBversion"
SlashCmdList["APHESLOOTBROWSERVERSIONCHECK"] = function(arg) 
	ALB:CheckVersions()
end



ALB:RegisterEvent("ADDON_LOADED")
--ALB:RegisterEvent("PLAYER_ALIVE")
ALB:RegisterEvent("EJ_LOOT_DATA_RECIEVED")